package com.example.snut_system.controller;

import com.example.snut_system.common.AppResult;
import com.example.snut_system.common.ResultCode;
import com.example.snut_system.model.User;
import com.example.snut_system.services.IUserService;
import com.example.snut_system.utils.MD5Util;
import com.example.snut_system.utils.UUIDUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 666
 * Date: 2023-12-11
 * Time: 20:05
 */
@Slf4j
// API 描述
@Api(tags = "⽤⼾接⼝")
// 标识为了个Controller并且响应时返回Body中的数据
@RestController
// 指定路径映射
@RequestMapping("/user")
public class UserController {
    // 注⼊业务层
    @Resource
    private IUserService userService;
    // 指定接⼝URL映射
    @PostMapping("/register")
    public AppResult register(String username, String nickname, String
            password, String passwordRepeat) {
        if (StringUtils.isEmpty(username)
            || StringUtils.isEmpty(password)
            || StringUtils.isEmpty(passwordRepeat)
            || StringUtils.isEmpty(nickname)) {
// 记录⽇志
        log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
// 返回错误信息
        return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
    }
// 1.基本信息赋值
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
// 2.处理密码
// 2.1 校验密码和确认密码是否相等
        if (!password.equals(passwordRepeat)) {
// 记录⽇志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
// 返回错误信息
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
// 2.2 加密密码
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5(password, salt);
// 2.3 设置密码
        user.setPassword(encryptPassword);
        user.setSalt(salt);
// 3. 调⽤Service
        userService.createNormalUser(user);
// 4. 返回
        return AppResult.success();
    }
}